import { store } from "@/store";
import { defineStore } from "pinia";
import TaskAPI, { type TaskType, type TaskListQuery } from "@/api/task/task";

export const useTaskStore = defineStore("task", () => {
  const list = ref<TaskType[]>([]);
  const totalCount = ref(0);
  const totalPage = ref(0);

  const loading = reactive({
    list: false,
    detail: false,
    update: false,
    delete: false,
  });

  async function fetchList(params: TaskListQuery) {
    loading.list = true;
    try {
      const res = await TaskAPI.getTaskList(params);
      list.value = res.records;
      totalCount.value = res.total_count;
      totalPage.value = res.total_page;
    } finally {
      loading.list = false;
    }
  }

  async function fetchDetail(id: number) {
    loading.detail = true;
    try {
      return await TaskAPI.getTaskDetail(id);
    } finally {
      loading.detail = false;
    }
  }

  async function fetchUpdate(data: Partial<TaskType>) {
    loading.update = true;
    try {
      await TaskAPI.updateTask(data);
    } finally {
      loading.update = false;
    }
  }

  async function fetchDelete(id: number) {
    loading.delete = true;
    try {
      await TaskAPI.deleteTask(id);
    } finally {
      loading.delete = false;
    }
  }

  return {
    list,
    totalCount,
    totalPage,
    loading,
    fetchList,
    fetchDetail,
    fetchUpdate,
    fetchDelete,
  };
});

export const useTaskStoreHook = () => {
  return useTaskStore(store);
};
